package com.sd.ws;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlashAgentX {
    private WebSocketClient socket;
    /**坐席id***/
    private String g_OptId = "";
    /**企业id**/
    private String g_entId = "";
    /**tokenId**/
    private String g_TokenId = "";
    /**分机号**/
    private String g_extNum = "";

    private String isCallIngNum = "";

    public FlashAgentX(WebSocketClient socket,String agentId,String g_entId,String g_TokenId,String g_extNum) {
        this.socket = socket;
        this.g_OptId = agentId;
        this.g_entId = g_entId;
        this.g_TokenId = g_TokenId;
        this.g_extNum = g_extNum;
    }

    public String getG_OptId() {
        return g_OptId;
    }

    public void setG_OptId(String g_OptId) {
        this.g_OptId = g_OptId;
    }

    public String getG_entId() {
        return g_entId;
    }

    public void setG_entId(String g_entId) {
        this.g_entId = g_entId;
    }

    public String getG_TokenId() {
        return g_TokenId;
    }

    public void setG_TokenId(String g_TokenId) {
        this.g_TokenId = g_TokenId;
    }

    public WebSocketClient getSocket() {
        return socket;
    }

    public void setSocket(WebSocketClient socket) {
        this.socket = socket;
    }

    public String getG_extNum() {
        return g_extNum;
    }

    public void setG_extNum(String g_extNum) {
        this.g_extNum = g_extNum;
    }

    /**
     * 日志记录
     */
    public enum SVCCODE{//定义交易密码
        SVCCODE_CHECKIN("1001","签入"),
        SVCCODE_CHECKIN2("1002","签入"),
        SVCCODE_CALLSEAT("1003","咨询座席"),
        SVCCODE_CALLTOUSER("1004","咨询"),
        SVCCODE_CALLUSER("1005","呼叫"),
        SVCCODE_CHECKOUT("1006","签出"),
        SVCCODE_DROPTOUSER("1007","结束外线咨询"),
        SVCCODE_DROPUSER("1008","挂机"),
        SVCCODE_FREESEAT("1009","结束内线咨询"),
        SVCCODE_GOTOFLOW("1010","转流程"),
        SVCCODE_HOLDERUSER("1011","保持"),
        SVCCODE_INMEET("1012","会议"),
        SVCCODE_INSERT("1013","插话=会议"),
        SVCCODE_MONITER("1014","监听"),
        SVCCODE_OFFLINE("1015","下线"),
        SVCCODE_ONLINE("1016","在线"),
        SVCCODE_OUTINSERT("1017","在线"),
        SVCCODE_OUTMEET("1018","在线"),
        SVCCODE_OUTMONITER("1019","在线"),
        SVCCODE_PLAYDTMF("1020","在线"),
        SVCCODE_REGISTAGCINFO("1021","在线"),
        SVCCODE_ROBCALL("1022","在线"),
        SVCCODE_SETBUSY("1023","在线"),
        SVCCODE_STOPCALL("1024","强拆其他坐席"), //9.5.6   强拆其他坐席
        SVCCODE_TOCHECKIN("1025","强拆其他坐席"),
        SVCCODE_TOCHECKOUT("1026","强拆其他坐席"),
        SVCCODE_TRANSSEAT("1027","强拆其他坐席"),
        SVCCODE_UNHOLDERUSER("1028","强拆其他坐席"),
        SVCCODE_RECOVER("1029","强拆其他坐席"),
        SVCCODE_WHISPER("1030","耳语"), // 耳语
        SVCCODE_OUTWHISPER("1031","结束耳"), //结束耳语
        SVCCODE_TOSETBUSY("1032","代示忙或闲"), //代示忙或闲
        SVCCODE_AUTHVERIFY("1100","鉴权成功"), //鉴权成功
        SVCCODE_HEARTBEAT("1101","获取坐席状态"), // 获取坐席状态
        SVCCODE_GETAGENTSTATUS("1102","获取坐席状态"), // 获取坐席状态
        SVCCODE_EVENT_AGENTSTATUS("1103","获取坐席状态"), // 获取坐席状态
        SVCCODE_EVENT_CALLINFO("1104","获取坐席通话信息"), // 获取坐席通话信息
        SVCCODE_EVENT_RING("1105","电话振"), // 电话振铃
        SVCCODE_EVENT_ANSWER("1106","电话接听"), // 电话接听
        SVCCODE_EVENT_HUNGUP("1107","电话挂机"), // 电话挂机
        SVCCODE_EVENT_RING3("1108","获取坐席通话信息"), // 获取坐席通话信息
        SVCCODE_EVENT_ANSWER3("1109","获取坐席通话信息"), // 获取坐席通话信息
        SVCCODE_EVENT_HUNGUP3("1110","获取坐席通话信息"), // 获取坐席通话信息
        SVCCODE_EVENT_BECHECKOUT("1111","获取坐席通话信息"),//
        SVCCODE_GETAGENTMESSAGE("1112","获取坐席状态"), // 获取坐席状态
        SVCCODE_GETCALLEVENT_STATUS("1113","获取坐席状态"),
        SVCCODE_GETSTATEEVENT_STATUS("1115","获取坐席状态"),
        SVCCODE_GETAGENTLIST("2001","获取坐席状态"),
        SVCCODE_GETENTQUEINFO("2002","获取坐席状态");

        private String value;
        private String name;
        SVCCODE(String value,String name){
          this.value = value;
          this.name = name;
        }
    }
    private static final Logger log = LoggerFactory.getLogger(FlashAgentX.class);
    private static final String SVCCODE_CHECKIN = "1001";
    private static final String SVCCODE_CHECKOUT = "1006";
    private static final String SVCCODE_CALLUSER = "1005";
    private static final String  g_masterUri = "";
    private static final String g_slaveUri = "";
    private static final String g_uri = "";

    private static final String g_entpwd="";
    private static final String g_agentPwd = "";
    private static final String g_willdoSendbuff = "";
    private static final String g_callEvent = null;
    private static final String g_callState = null;
    /**
     * 坐席签入
     */
    public void checkin(String agentPwd,String extNum,String entPwd,String outsecond){
        JSONObject jsonObject = new JSONObject();
        /**
         * json封装
         */
        jsonObject.put("hotline","");
        jsonObject.put("pass",agentPwd);
        jsonObject.put("station",extNum);
        jsonObject.put("entpwd",entPwd);
        jsonObject.put("stationtype",0);
        jsonObject.put("checkintype",0);
        jsonObject.put("outsecond",outsecond);

        String trBody = jsonObject.toJSONString();
        String buf = this.packHost(FlashAgentX.SVCCODE_CHECKIN, trBody);
        this.doSend(buf);
    }

    public String packHost(String trCode,String trBody) {
        if ("".equals(this.g_OptId)) {
            log.error("pack error " + trCode + " flashagentx not init !");
            return "";
        }
        String headStr = "\"head\":{\"hostcode\":\"" + trCode + "\",\"entid\":" + this.g_entId + ",\"optid\":\"" + this.g_OptId + "\",\"tokenid\":\"" + this.g_TokenId + "\"}";
        String bodyStr = "\"body\":" + trBody;
        String doSendBuffer = "{" + headStr + "," + bodyStr + "}";
        log.info("doSend:" + doSendBuffer);
        return doSendBuffer;
    }

    /**
     * 签出
     */
    public void checkout() {
        String trBody = "{\"message\":\"\"}";
        String buf = this.packHost(FlashAgentX.SVCCODE_CHECKOUT, trBody);
        this.doSend(buf);
    }
    /**
     * 发送消息
     * @param buffer
     */
    public void doSend(String buffer) {
        if (buffer == "") return;
        if (this.socket != null && this.socket.isOpen()) {
            try {
                this.socket.send(buffer);
            } catch(Exception ex) {
                log.error("doSend error:",ex);
            }
        } else {
            if(this.socket==null){
                return;
            }
            ReadyState readyStateObj = this.socket.getReadyState();
            String readyState = this.socket.getReadyState().name();
            System.out.println("readyState Object: "+readyStateObj);
            System.out.println("readyState: "+readyState);
            System.out.println("isOpen: "+this.socket.isOpen());
            System.out.println("ReadyState.NOT_YET_CONNECTED: "+ReadyState.NOT_YET_CONNECTED);

            System.out.println("ReadyState.NOT_YET_CONNECTED equeals: "+ReadyState.NOT_YET_CONNECTED.equals(readyState));
            System.out.println("ReadyState.NOT_YET_CONNECTED toString equeals: "+ReadyState.NOT_YET_CONNECTED.toString().equals(readyState));
            System.out.println("ReadyState.NOT_YET_CONNECTED name equeals: "+ReadyState.NOT_YET_CONNECTED.name().equals(readyState));
            if (!this.socket.isOpen()) {
                if (ReadyState.NOT_YET_CONNECTED.toString().equals(readyState)) {
                    try {
                        this.socket.connect();
                    } catch (IllegalStateException e) {
                    }
                } else if (ReadyState.CLOSING.toString().equals(readyState) || ReadyState.CLOSED.toString().equals(readyState)) {
                    this.socket.reconnect();
                }
            }

            try {
                Thread.sleep(100l);
            }catch (Exception e){
                e.printStackTrace();
            }
            this.socket.send(buffer);
        }
    };

    /**
     * 发起呼叫
     * @param telno 电话
     * @param exinfo 扩展信息
     */
    public void makecall(String telno, String exinfo){
        if(StringUtils.isBlank(telno)){
            return;
        }
        String telno2 = telno.trim();
        if (this.isCallIngNum == telno2) {
            log.info("Calling " + telno2 + "，稍后再试!");
            return;
        }
        this.isCallIngNum = telno2;
        /*var trBody = { //交易请求正文
                "telno": telno2,
            "exinfo": exinfo
        };*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("telno",telno2);
        jsonObject.put("exinfo",exinfo);
        String trBody = jsonObject.toJSONString();
        String buf = this.packHost(FlashAgentX.SVCCODE_CALLUSER, trBody);
        this.doSend(buf);
        try {
            Thread.sleep(3000L);
            this.isCallIngNum="";
        }catch (Exception e){
             e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "FlashAgentX{" +
                "socket=" + socket +
                ", g_OptId='" + g_OptId + '\'' +
                ", g_entId='" + g_entId + '\'' +
                ", g_TokenId='" + g_TokenId + '\'' +
                '}';
    }
}
